// pages/article/index.js
const app = getApp()
const db = wx.cloud.database()

Page({
  data: {
    article: null,
    loading: true,
    isCollected: false,
    defaultCover: '/images/default-cover.png'
  },

  onLoad: function (options) {
    if (options.id) {
      this.articleId = options.id
      this.loadArticleDetail()
      this.checkCollectionStatus()
    } else {
      wx.showToast({
        title: '文章ID不存在',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  // 加载文章详情
  loadArticleDetail: function () {
    wx.cloud.callFunction({
      name: 'getArticleDetail',
      data: {
        id: this.articleId
      }
    }).then(res => {
      if (res.result && res.result.data) {
        const article = res.result.data
        // 格式化时间
        article.createTime = app.formatTime(article.createTime)
        
        this.setData({
          article,
          loading: false
        })
        
        // 设置页面标题
        wx.setNavigationBarTitle({
          title: article.title || '文章详情'
        })
      } else {
        this.setData({
          loading: false
        })
        wx.showToast({
          title: '文章不存在或已删除',
          icon: 'none'
        })
      }
    }).catch(err => {
      console.error('获取文章详情失败', err)
      this.setData({
        loading: false
      })
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
    })
  },

  // 检查收藏状态
  checkCollectionStatus: function () {
    const openid = app.globalData.openid
    if (!openid) {
      console.log('用户未登录，无法获取收藏状态')
      return
    }

    db.collection('collections')
      .where({
        _openid: openid,
        articleId: this.articleId
      })
      .get()
      .then(res => {
        this.setData({
          isCollected: res.data.length > 0
        })
      })
      .catch(err => {
        console.error('获取收藏状态失败', err)
      })
  },

  // 收藏/取消收藏
  toggleCollection: function () {
    const openid = app.globalData.openid
    if (!openid) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    wx.cloud.callFunction({
      name: 'toggleCollection',
      data: {
        articleId: this.articleId
      }
    }).then(res => {
      const { success, collected } = res.result
      if (success) {
        this.setData({
          isCollected: collected
        })
        wx.showToast({
          title: collected ? '收藏成功' : '已取消收藏',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        })
      }
    }).catch(err => {
      console.error('收藏操作失败', err)
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      })
    })
  },

  // 分享功能
  onShareAppMessage: function () {
    const { article } = this.data
    return {
      title: article ? article.title : '精彩文章分享',
      path: `/pages/article/index?id=${this.articleId}`
    }
  }
})